package TTEST;

import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.TreeSet;

import javax.swing.DefaultListModel;
import javax.swing.JDesktopPane;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JInternalFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JViewport;
import javax.swing.KeyStroke;

import a.jframe.InternalFrame;
import Files.File_;

public class InternalFrameDemo extends javax.swing.JFrame implements
		ActionListener {
	private static InternalFrameDemo instance;

	public static InternalFrameDemo get() {
		return instance;
	}

	static List<LabWindow> allconnections = new ArrayList<LabWindow>();

	public static List<LabWindow> getAllConnections() {
		return allconnections;
	}

	private static JDesktopPane desktop;
	private WindowAdapter windowAdapter;
	private ReadCommandsThread rct;

	public InternalFrameDemo() {
		super("CLI > GUI Interface Test Tool");
		instance = this;
		if (new File_().isbasedirectory()) {
			System.out.println("ok");
		}
		windowAdapter = new WindowAdapter() {
			public void windowClosing(WindowEvent we) {
				for (LabWindow lab : allconnections) {

					while (lab.ct.isAlive()) {
						lab.ct.td.rc.interrupt();
						System.out
								.println("Thread which was responsible for reading output stream has been stopped");
						try {
							Thread.sleep(500);
						} catch (Exception e) {
						}
						;
						System.out.println("Waiting for stop connection with "
								+ lab.host);
						lab.ct.interrupt();
					}
					System.out.println("Connection with " + lab.host
							+ " has been closed");
				}
				/*
				 * while(rct.isAlive()) { try{
				 * Thread.sleep(1000);}catch(Exception e ) {};
				 * System.out.println("Waiting for stop all threads"); }
				 */
				System.out.println("End work of CLI application");
				// setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
				System.exit(0);
			}
		};

		addWindowListener(windowAdapter);
		// Make the big window be indented 50 pixels from each edge
		// of the screen.
		int inset = 50;
		Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
		setBounds(inset, inset, screenSize.width - inset * 2, screenSize.height
				- inset * 2);

		// Set up the GUI.
		desktop = new JDesktopPane(); // a specialized layered pane
		// createFrame(); //create first "window"
		setContentPane(desktop);
		setJMenuBar(createMenuBar());

		// Make dragging a little faster but perhaps uglier.
		desktop.setDragMode(JDesktopPane.OUTLINE_DRAG_MODE);
		a = getContentPane().getComponents();
	}

	void AddToMenu(JMenu value) {
		menuBar.add(value);
	}

	private static JMenuBar menuBar = new JMenuBar();

	static void refreshMenu() {

	}

	/**
	 * 0-label
	 * 
	 * @param array
	 */
	JMenuItem add_sub_menu(Map<String, Object> array) {
		JMenuItem menuItem;
		menuItem = new JMenuItem(array.get("name").toString());
		menuItem.setMnemonic((Integer) (array.get("shortkey")));
		menuItem.setAccelerator(KeyStroke.getKeyStroke(
				(Integer) array.get("shortkey"), ActionEvent.ALT_MASK));
		menuItem.setActionCommand(array.get("actionCommand").toString());
		menuItem.addActionListener(this);
		return menuItem;
	}

	JMenu menu;

	void menu_labs() {
		File_.onlyReadFile(0);
		File_.onlyReadFile(1);
		int counter = 0;
		if (new File_().openFile(1)) {
			File_.common_map_labs = new File_().readF(1);
			if (!File_.common_map_labs.isEmpty()) {
				for (Entry<String, String> t : File_.common_map_labs.entrySet()) {
					JMenuItem temp = new JMenuItem(t.getKey());
					temp.setName(t.getKey());
					temp.setActionCommand("definedlabs");
					temp.setName("lab" + counter++);
					temp.addActionListener(this);
					menu.add(temp);
				}
			}
		}
	}

	public void aaa() {
		for (Component c : menu.getMenuComponents()) {
			menu.remove(c);
		}
		createSubmenu();
	}

	/**
	 * generate menu for all labs
	 */
	void createFirstMenu() {
		menu = new JMenu("Labs");
		menu.setMnemonic(KeyEvent.VK_D);
		AddToMenu(menu);
		menu = new JMenu("Settings");
		menu.setMnemonic(KeyEvent.VK_S);
		AddToMenu(menu);
		JMenuItem menuItem;
		createSubmenu();
	}

	void createSubmenu() {
		menu_labs();
		Map<String, Object> m = new HashMap<String, Object>();
		m.put("name", "Labs");
		m.put("shortkey", KeyEvent.VK_N);
		m.put("actionCommand", new String("commands"));
		menu.add(add_sub_menu(m));
		
		m.clear();
		m.put("name", "Commands");
		m.put("shortkey", KeyEvent.VK_L);
		m.put("actionCommand", new String("labs"));
		menu.add(add_sub_menu(m));
		
		m.clear();
		m.put("name", "Quit");
		m.put("shortkey", KeyEvent.VK_Q);
		m.put("actionCommand", new String("quit"));
		menu.add(add_sub_menu(m));
	}

	protected JMenuBar createMenuBar() {
		createFirstMenu();

		return menuBar;
	}

	static String _lab;

	// React to menu selections.
	public void actionPerformed(ActionEvent e) {
		if ("quit".equals(e.getActionCommand())) {
			for (LabWindow lab : allconnections) {

				while (lab.ct.isAlive()) {
					lab.ct.td.rc.interrupt();
					System.out
							.println("Thread which was responsible for reading output stream has been stopped");
					try {
						Thread.sleep(500);
					} catch (Exception ee) {
					}
					;
					System.out.println("Waiting for stop connection with "
							+ lab.host);
					lab.ct.interrupt();
				}
				System.out.println("Connection with " + lab.host
						+ " has been closed");
			}
			/*
			 * while(rct.isAlive()) { try{ Thread.sleep(1000);}catch(Exception
			 * e1 ) {}; System.out.println("Waiting for stop all threads"); }
			 */
			System.out.println("End work of CLI application");
			System.exit(0);
		}
		if ("labs".equals(e.getActionCommand())) {
			crealeLab(((JMenuItem) e.getSource()).getText());
		}
		if ("commands".equals(e.getActionCommand())) {
			crealeCommands();
		}
		if ("definedlabs".equals(e.getActionCommand())) {
			//cc.start();
		//	createFrame(((JMenuItem) e.getSource()).getText());
			createFrame(((JMenuItem) e.getSource()).getText(),true);
		}
	}

	protected void crealeLab(String name) {
		Commands_Labs_ frame = new Commands_Labs_(0/* ,"Labs" */);
		frame.setVisible(true);
		desktop.add(frame);
	}

	static Component[] a;

	static void ff() {
		JInternalFrame ifr = null;
		JInternalFrame[] a = desktop.getAllFrames();
		JScrollPane ss = null;
		for (JInternalFrame ii : a) {
			System.out.println("IIII" + ii);
			Component[] components1 = ii.getContentPane().getComponents();
			Component component = null, cc = null;
			for (int i = 0; i < components1.length; i++) {
				component = components1[i];
				if (component instanceof JTabbedPane) {
					// pobierz wszystkie taby
					int count = ((JTabbedPane) component).getTabCount();
					for (int i1 = 0; i1 < count; i1++) {
						Component com = ((JTabbedPane) component)
								.getComponentAt(i1);
						if (com instanceof JTabbedPane) // {
							System.out.println(((JTabbedPane) com)
									.getTitleAt(0));
						if (com instanceof JPanel) {
							System.out.println(((JPanel) com).getName());
							Component[] components = ((JPanel) com)
									.getComponents();
							// get all components and set them
							for (int aa = 0; aa < components.length; aa++) {
								System.out.println("C" + components[aa]);
								if (components[aa].getName() != null) {
									System.out
											.println(components[aa].getName());
									if (components[aa].getName() == "Lista") {
										ss = (JScrollPane) components[aa];
										JViewport viewport = ss.getViewport();
										Component[] mm = viewport
												.getComponents();
										for (int x = 0; x < mm.length; x++) {
											cc = mm[x];
											System.out.println("..."
													+ cc.getName());
											JList tt = (JList) cc;
											DefaultListModel dlm = (DefaultListModel) tt
													.getModel();
											for (int y = 0; y < dlm.size(); y++)
												System.out.println(dlm
														.getElementAt(y)
														.toString());
											// read list again
											Map<String, String> c = File_.common_map_commands;
											dlm.clear();
											if (!c.isEmpty()) {
												for (Entry<String, String> entry : c
														.entrySet()) {
													dlm.addElement(entry
															.getKey());
												}
											}
											tt.setModel(dlm);
										}
									}
								}
							}

						}
						// }
					}
				}
			}
		}

	}

	public void updateList() {
		a = getContentPane().getComponents();
		/*
		 * Component[] components1 = a; Component component = null; for (int i =
		 * 0; i < components1.length; i++) { component = components1[i]; if
		 * (component instanceof JTabbedPane) { int count = ((JTabbedPane)
		 * component).getTabCount(); for (int i1 = 0; i1 < count; i1++) {
		 * Component com = ((JTabbedPane) component) .getComponentAt(i1);
		 * System.out.println(">>>"+com); } } }
		 */
	}

	void crealeCommands() {
		Commands_Labs_ frame = new Commands_Labs_(1/* ,"Commands" */);
		frame.setVisible(true);
		desktop.add(frame);
	}

	static void open() {
		desktop.add(new Commands_Labs_(0));
	}

	static Map<String, Map<String, String>> maps = new HashMap<String, Map<String, String>>();

	static String gen(Map<String, String> a, String tab) {
		return "";
	}

	/**
	 * add <b>parameter name</b> and <b>valuesOfParameterName</b><br/>
	 * <br/>
	 * tab -> U(Upload)|P(Provision
	 * 
	 * @param parameterName
	 * @param valuesOfParameterName
	 * @param tab
	 */
	static void addValueToCommonMap(String parameterName,
			String valuesOfParameterName, String tab) {
		Map<String, String> rr = new HashMap<String, String>();
		if (maps.containsKey(tab))
			rr = maps.get(tab);
		rr.put(parameterName, valuesOfParameterName.toString());
		maps.put(tab, rr);
		System.out.println("addValueToCommonMap");
	}

	static String mergeStandardAndActualValues(Map<String, String> a, String tab) {
		String com = "";
		for (String key : ((Map<String, String>) maps.get(tab)).keySet()) {
			com += (!(((Map<String, String>) maps.get(tab)).get(key).equals(a
					.get(key))) ? (a.get(key).equals("")) ? " " : "-"
					+ key.substring(2) + " " + a.get(key) + " " : "");
		}
		return com;
	}

	/**
	 * array [0]->tab-P/U|[1]->key
	 * 
	 * @param array
	 * @return
	 */
	static String getStandardPropertyForParamater(String... array) {
		return ((Map<String, String>) maps.get(array[0])).get(array[1]);
	}

	/**
	 * Returns all parameters for operation<br/>
	 * Provision,Upload
	 * 
	 * @param tab
	 *            (Provision/Upload)
	 * @return Map<String,String>
	 */
	static Map<String, String> getMap(String tab) {
		return maps.get(tab);
	}

	public static P polaczenie = new P();

	// Create a new internal frame.
	Thread cc=new Thread(new Runnable() {
		P aa = new P();
		
		@Override
		public void run() {
			System.out
			.println("WYKONANO THREAD.............................................");
			aa.setVisible(true);
		}
		public void c(String h) {
			aa.setStatus(h);
		}
	});
	JDialog dialog = new JDialog();
	void dialog()
	{
	JLabel label = new JLabel("Please wait...");
	dialog.setLocationRelativeTo(null);
	dialog.setTitle("Please Wait...");
	dialog.add(label);
	dialog.pack();
	}
	protected void createFrame(String temp,boolean offline)
	{
		localoffline=offline;
		if(offline)
			temp+=" &"+String.valueOf(offline);
		createFrame(temp); 
		
	}
	private boolean localoffline=false;
	protected void createFrame(String temp) {
		// polaczenie.setStatus("Connecting....");
		//Komunikat k = new Komunikat();
		/*cc.setDaemon(true);
		cc.start();*/
		
		
		try {
			Thread.sleep(2000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		/*
		 * P aa=new P(); aa.setStatus("Trying to connect....."); aa.show();
		 */
		// aa.setVisible(true);
		
		  LabWindow frame=new LabWindow(temp);
		  if (localoffline )
		  {
		  while(!frame.polaczenie_z_ip){
		  try { if( frame.ct.getPRACA() ) { 
			  //k.c("Connection to the lab is ok");
		  Thread.sleep(200); break; }
		  
		  Thread.sleep(200); } catch (InterruptedException e) {
		  e.printStackTrace(); }}
		  
		  try { Thread.sleep(2000); } catch (InterruptedException e) {
		  e.printStackTrace(); } if ( frame.polaczenie_z_ip &&
		  frame.ct.getPRACA() ) { allconnections.add(frame);
		  frame.setVisible(true); desktop.add(frame); } else { }
		  }
		 

	}

	// Quit the application.
	protected void quit() {
		System.exit(0);
	}

	/**
	 * Create the GUI and show it. For thread safety, this method should be
	 * invoked from the event-dispatching thread.
	 */
	private static void createAndShowGUI() {
		// Make sure we have nice window decorations.
		JFrame.setDefaultLookAndFeelDecorated(true);

		// Create and set up the window.
		InternalFrameDemo frame = new InternalFrameDemo();
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

		// Display the window.
		frame.setVisible(true);
	}

	public static void main(String[] args) {
		// Schedule a job for the event-dispatching thread:
		// creating and showing this application's GUI.
		javax.swing.SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				createAndShowGUI();
			}
		});
	}

}
